// created by hanbo
// created at 2017/07/25

#ifndef __TEST_THREAD_H__
#define __TEST_THREAD_H__

#include <map>
#include <mutex>
#include <memory>
#include <condition_variable>

#include "SimpleThread.h"

static std::string generate_uuid()
{
    static std::atomic<int> uuid = 0;
    return std::to_string(++uuid);
}

// 动态人脸中含有detect和query task
struct Task
{
    int     data_;
    bool    is_done_;
}
typedef std::shared_ptr<Task> TaskPtr;

class TestThread : public SimpleThread
{
public:
    TestThread(bool startRightNow = true);
    
    ~TestThread();

    // 提供给调用者的同步接口
    // 将参数打包给调用者，并同步等待调用
    void do_sth(int a)
    {
        std::string task_uuid = generate_uuid();
        TaskPtr task;
        task->data_ = a;
        task->is_done_ = false;
        bool& is_done = task->is_done_;
        {
            std::unique_lock<std::mutex> lock(map_mutex_);
            task_map_.insert(std::make_pair(task_uuid, task_map_));

            map_cond_.notify_one();
        }

        {
            std::unique_lock<std::mutex> lock(caller_mutex_);
            while (!is_done) {
                caller_cond_.wait(caller_mutex_, std::chrono::seconds(1));
            }
        }
        
        //done

        return;
    }

private:
    // 真正的detect和query实现，不由调用者线程执行
    void do_sth_impl(int a) {

    }


protected:
    virtual void do_run()
    {
        while (!is_stopped()) {
            // getq

            // call do_sth_impl

            caller_cond_.notify_all();
        }
    }

private:
    std::map<std::string, TaskPtr>      task_map_;
    std::mutex                      map_mutex_;
    std::condition_variable         map_cond_;
    std::mutex                      caller_mutex_;
    std::mutex                      caller_cond_;
};

#endif // __TEST_THREAD_H__